import Taro from "@tarojs/taro";
import React, { useState } from "react";

enum ErrorType {
    "ok",
    "密码错误",
    "用户未注册"
}

Taro.cloud.init();
interface ResopnseType<Data> {
    msg: string,
    state: number,
    data: Data
}
type ID = Taro.DB.Document.DocumentId;
let db = Taro.cloud.database();
interface userRegister {
    username: string,
    password: string,
    phone: string
}
export function register(data: userRegister) {
    return new Promise((resolve, reject) => {
        db.collection('user').add({
            data: {
                type: 0,
                ...data
            }
        }).then(_res => {
            let res: ResopnseType<{ id: Taro.DB.Document.DocumentId }> = {
                state: 0,
                data: {
                    id: _res._id
                },
                msg: 'ok'
            }
            resolve(res)
        }, rej => {
            let res: ResopnseType<undefined> = {
                state: -1,
                msg: rej.errMsg,
                data: undefined
            }
            reject(res)
        })
    })
}
interface userLogin {
    phone: string,
    password: string
}

export function login(data: userLogin) {
    return new Promise((resolve, reject) => {
        db.collection('user').where({
            phone: data.phone
        }).get().then((res: any) => {
            console.log(res);
            if (res.data.length === 0) {
                return reject({
                    state: ErrorType.用户未注册,
                    msg: '用户未注册',
                })
            }
            if (res.data[0].password == data.password) {
                resolve({
                    state: ErrorType.ok,
                    msg: 'ok',
                    data: {
                        "username": res.data[0].username,
                        "id": res.data[0]._id
                    }
                })
            } else {
                reject({
                    state: ErrorType.密码错误,
                    msg: '密码错误'
                })
            }
            // if(res.data[0])
        })
    })
}